﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：李弼翀
    //
    // 文件名：ChildUserList.aspx
    // 文件功能描述：子用户管理：提供新增子用户、修改子用户、删除子用户、查询子用户,锁定，修改权限等操作
    // 创建标识：李弼翀2009-03-30
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;

using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using System.Collections.Generic;
using HZ.DrugTrade.Model.Enum;
using System.Text;

namespace HZ.DrugTrade.Web.Admin
{
    public partial class ChildUserList : BasePage
    {

        public ChildUserList()
        {
            this.ModuleNo = Module.系统管理.ToString();
            this.PageOperateType = OperateType.子用户管理.ToString();
        }
        IBLL_User iu = Factory.BLL_User();
        string userIDIndex;
        HZ.DrugTrade.BLL.BLL_Log log = new BLL.BLL_Log();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                StoreCondition();
                bindUser();
            }
        }

        /// <summary>
        /// 定义绑定用户的方法
        /// </summary>
        private void bindUser()
        {
            //通过GetUser方法获取用户的Org
            User currentUser = CurrentAccount.GetUser();
            Org org = currentUser.Org;
            //判断用户所属机构是否为空
            if (org != null)
            {
                //获取查询条件，执行查询
                IBLL_User iu = Factory.BLL_User();
                //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
                int totalRecord = 0;
                HZ.DrugTrade.Model.Query.User queryUser = (HZ.DrugTrade.Model.Query.User)ViewState["v_user"];
                this.gvwChildUserList.PageSize = AspNetPager1.PageSize;
                this.gvwChildUserList.DataSource = iu.GetUserByWhere(queryUser, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalRecord);
                AspNetPager1.RecordCount = totalRecord;
                this.gvwChildUserList.DataBind();
            }
            else
            {
                PageError("用户无所属机构，无法查看其子用户！", "");
            }
        }

        private void StoreCondition()
        {
            //通过GetUser方法获取用户的Org
            User currentUser = CurrentAccount.GetUser();
            Org org = currentUser.Org;
            if (org != null)
            {
                HZ.DrugTrade.Model.Query.User user = new HZ.DrugTrade.Model.Query.User();
                user.IsAdmin = false;
                user.OrgID = org.OrgID;
                user.RoleID = currentUser.UserRole.RoleID;
                user.Username = this.txtChildUserName.Text.Trim();
                user.Userid = this.txtUserId.Text.Trim();
                if (this.ddlIsUsing.SelectedItem.Value.ToString() == "0")
                {
                    user.Isusing = false;
                }
                else if (this.ddlIsUsing.SelectedItem.Value.ToString() == "1")
                {
                    user.Isusing = true;
                }
                else
                {
                    user.Isusing = null;
                }

                if (this.ddlIsOnline.SelectedItem.Value.ToString() == "0")
                {
                    user.Isonline = false;
                }
                else if (this.ddlIsOnline.SelectedItem.Value.ToString() == "1")
                {
                    user.Isonline = true;
                }
                else
                {
                    user.Isonline = null;
                }
                if (HZ.Common.MyValidate.IsDate(this.txtLoginFrom.Text.Trim()))
                {
                    user.LastlogintimeFrom = Convert.ToDateTime(txtLoginFrom.Text.Trim());
                }
                if (HZ.Common.MyValidate.IsDate(txtLoginTo.Text.Trim()))
                {
                    user.LastlogintimeTo = Convert.ToDateTime(txtLoginTo.Text.Trim());
                }
                user.SortFields = "Userid ASC";
                ViewState["v_user"] = user;
            }

        }

        /// <summary>
        /// 调用方法，绑定用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            StoreCondition();
            bindUser();
        }

        /// <summary>
        /// 添加子用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddChildUser_Click(object sender, EventArgs e)
        {
            this.Response.Redirect("ChildUserAdd.aspx");
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwChildUserList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                string strUserID = e.CommandArgument.ToString();

                int flag = iu.DeleteUser(strUserID);
                if (flag == 0)
                {
                    HZ.Web.MessageBox.Show("删除失败！");
                }
                if (flag == 1)
                {
                    log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("删除角色{0}", strUserID) });
                    HZ.Web.MessageBox.AlertAndRefresh("删除成功！");
                }
                if (flag == 2)
                {
                    HZ.Web.MessageBox.Show("该用户不存在！");
                }
            }
            if (e.CommandName == "Lock")
            {
                userIDIndex = Convert.ToString(e.CommandArgument);
                IBLL_User iu = Factory.BLL_User();

                //判定用户锁定、解锁情况
                try
                {
                    User aUser = iu.GetUserByUserID(userIDIndex);
                    if (aUser.IsUsing)
                    {
                        if (iu.LockUser(userIDIndex))
                        {
                            HZ.Web.WebUtil.Alert("用户" + userIDIndex + "已被锁定！",this);
                        }
                    }
                    else
                    {
                        if (iu.UnblockUser(userIDIndex))
                        {
                            HZ.Web.WebUtil.Alert("用户" + userIDIndex + "已被解锁！",this);
                        }
                    }
                    bindUser();
                }
                catch (Exception ex)
                {
                    HZ.Web.WebUtil.Alert("用户" + userIDIndex + "锁定失败！" + ex.Message,this);
                }
            }
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            bindUser();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.gvwChildUserList.EditIndex = -1;
            this.bindUser();
        }

        /// <summary>
        /// 绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwChildUserList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                User aUser = iu.GetUserByUserID(e.Row.Cells[1].Text.Trim());
                LinkButton lb = (LinkButton)e.Row.Cells[4].FindControl("lbnLock");
                if (lb != null)
                {
                    if (aUser.IsUsing)
                    {
                        lb.Text = "锁定";
                    }
                    else
                    {
                        lb.Text = "解锁";
                    }
                }
            }

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwChildUserList_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.gvwChildUserList.EditIndex = e.NewEditIndex;
            this.bindUser();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwChildUserList_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (Page.IsValid)
            {
                int rowIndex = e.RowIndex;
                string userId = this.gvwChildUserList.DataKeys[rowIndex].Value.ToString();
                string strUserName = ((TextBox)this.gvwChildUserList.Rows[rowIndex].FindControl("txtUserName")).Text.Trim();
                if (string.IsNullOrEmpty(strUserName))
                {
                    HZ.Web.WebUtil.Alert("用户名称不能为空！",this);
                    ((TextBox)gvwChildUserList.Rows[rowIndex].FindControl("txtUserName")).Focus();
                    return;
                }
                User user = new User();
                user.UserID = userId;
                user.UserName = strUserName;
                if (iu.UpdateUser(user) == 1)
                {
                    //重新绑定列表
                    this.gvwChildUserList.EditIndex = -1;
                    this.bindUser();
                }
                else
                {
                    PageError("更新失败！", "");
                }
            }
        }

        /// <summary>
        /// 批量锁定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatLock_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkChildUser"];//获取选中的用户ID，形式如 01,02,03
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);//分割成数组
                List<string> userIds = new List<string>();            //添加到List中
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                //批量锁定
                if (iu.LockUser(userIds))
                {
                    bindUser();
                    //PageInfo("成功锁定选定用户！", "");
                }
                else
                {
                    PageError("锁定用户失败！", "");
                }
            }
        }

        /// <summary>
        /// 批量初始化密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatResetPws_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkChildUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                if (iu.InitPassword(userIds, Constants.USER_DEFAULT_PWS))
                {
                    PageInfo("用户" + strChkUsers + "的密码已被初始化为" + Constants.USER_DEFAULT_PWS, "");
                }
                else
                {
                    PageError("密码初始化失败", "");
                }
            }
        }

        /// <summary>
        /// 批量解锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatUnLock_Click(object sender, EventArgs e)
        {
            string strChkChildUsers = Request["chkChildUser"];
            if (!string.IsNullOrEmpty(strChkChildUsers))
            {
                string[] arryUsers = strChkChildUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                //批量锁定
                if (iu.UnblockUser(userIds))
                {
                    bindUser();
                    //PageInfo("成功解锁选定用户！", "");
                }
                else
                {
                    PageError("解锁用户失败！", "");
                }
            }
        }

        protected void lbnLock_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 简单查询与高级查询间的切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                txtLoginFrom.Text = "";
                txtLoginTo.Text = "";
                txtChildUserName.Text = "";
                ddlIsOnline.SelectedIndex = -1;
                ddlIsUsing.SelectedIndex = -1;
            }
        }

        /// <summary>
        /// 批量设置用户权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatSetOperate_Click(object sender, EventArgs e)
        {
             string strChkChildUsers = Request["chkChildUser"];
             if (!string.IsNullOrEmpty(strChkChildUsers))
             {
                 Response.Redirect("ChildUserOperateBatch.aspx?uids="+strChkChildUsers+"&pid="+CurrentAccount.GetUser().UserID);
             }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //通过GetUser方法获取用户的Org
            User currentUser = CurrentAccount.GetUser();
            Org org = currentUser.Org;
            //判断用户所属机构是否为空
            if (org != null)
            {
                HZ.DrugTrade.Model.Query.User user = (HZ.DrugTrade.Model.Query.User)ViewState["v_user"];
                string sql_temp = @"SELECT UserID 用户ID,UserName 用户名称,case IsUsing when 1 then '启用' when 0 then '禁用' end as 是否启用 FROM View_UserRole WHERE 1=1 ";

                StringBuilder sbWhere = new StringBuilder(sql_temp);

                if (user != null)
                {
                    if (!string.IsNullOrEmpty(user.Userid))
                    {
                        sbWhere.AppendFormat(" AND  UserID = '{0}'", user.Userid.Trim()); // 增加UserID查询条件
                    }
                    if (!string.IsNullOrEmpty(user.Username))
                    {
                        sbWhere.AppendFormat(" AND  UserName LIKE '%{0}%'", user.Username.Trim()); // 增加UserName查询条件
                    }
                    if (!string.IsNullOrEmpty(user.OrgID))
                    {
                        sbWhere.AppendFormat(" AND  OrgID = '{0}'", user.OrgID.Trim()); // 增加OrgID查询条件
                    }
                    if (!string.IsNullOrEmpty(user.RoleID))
                    {
                        sbWhere.AppendFormat(" AND  RoleID = '{0}'", user.RoleID.Trim()); // 增加RoleID查询条件
                    }
                    if (user.IsAdmin != null)
                    {
                        sbWhere.AppendFormat(" AND  IsUserAdmin = {0}", (bool)user.IsAdmin ? 1 : 0); // 增加IsUserAdmin是否主用户查询条件
                    }
                    if (user.Isusing != null)
                    {
                        sbWhere.AppendFormat(" AND  Isusing = {0}", (bool)user.Isusing ? 1 : 0); // 增加Isusing查询条件
                    }
                    if (user.Isonline != null)
                    {
                        sbWhere.AppendFormat(" AND  Isonline =  {0}", (bool)user.Isonline ? 1 : 0); // 增加Isonline查询条件
                    }
                    if (user.LastlogintimeFrom != null)
                    {
                        sbWhere.AppendFormat(" AND  Lastlogintime >= '{0}'", user.LastlogintimeFrom.ToString()); // 增加LastlogintimeFrom查询条件
                    }

                    if (user.LastlogintimeTo != null)
                    {
                        sbWhere.AppendFormat(" AND  Lastlogintime <= '{0}'", user.LastlogintimeTo.ToString());  // 增加LastlogintimeTo查询条件
                    }

                }
                HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sbWhere.ToString()), "", "调价计划.xls");
            }
        }
    }
}
